2012-10-26 27 views
0

請幫助我與knockout.js問題:將數據保存在knockout.js中

爲什麼變量currentObject是未發現的?我如何將當前選定的對象保存在某個變量中?

我必須遵循HTML視圖下下拉列表:

<select data-placeholder="Select object" class="span5" id="objects" data-bind="options: objects, optionsText: 'Name', optionsValue: 'Id', value: currentObject"> 
        <option></option> 
</select> 

模型視圖:

function baseViewModel() { 
    self.objects = ko.observableArray([]); 

    ... 

    self.currentObject = ko.observable(); 

    ... 



    self.func = function() { 

     //allert(self.objects()[0].Name) //return correct Name 
     alert(self.currentObject().Name) //returns undefinded 


    } 

} 
+1

是什麼'self.currentObject()'返回? –

+0

你實際上是在定義'self'嗎?它看起來不像。 – Tyrsius

+0

「var self = this;」before「self.objects = ko.observableArray([]);」 – user1726559

回答

0

在數據綁定,你有value: currentObject這的確會做currentObject之間的雙向綁定和選擇的

select的值設置爲選定選項對象的Id字段(因爲數據綁定中的optionsValue: 'Id')。 因此,currentObject將被設置爲所選對象的Id字段,這就是爲什麼.Name讓你不確定。

我建議根本不要使用optionsValue,這樣KO就會處理這個值,它就好像選擇框的值是實際選定的對象,並且value: currentObject會正確地將currentObject設置爲選定的對象。 (如果你想使用optionsValue,後來才知道,currentObject將被設置爲對象的領域,而不是對象本身)

小提琴:http://jsfiddle.net/antishok/KXhem/78/