我的HTML如下:
<div id="spotPrices">
<label class="spotLabel">Oil (WTI) $/bbl:</label>
<INPUT type="text" id="OilSpotPrice" Size=8>
</div>
和我的JavaScript:
ShowSpotPrices = Backbone.Model.extend({
defaults: {
wti: "0.00",
},
url: function () {
return 'http://localhost:4000/api/getSpotPrices';
},
initialize: function () {
console.log("Initialized ShowSpotPrices Model...")
}
});
ShowSpotPricesView = Backbone.View.extend({
el: '#spotPrices',
initialize: function() {
this.listenTo(this.model, 'sync change', this.render);
this.model.fetch();
this.render();
},
render : function() {
//this.$("#OilSpotPrice").html("27.45");
this.$("#OilSpotPrice").html(this.model.get('wti'));
return this;
}
});
var spotPrices = new ShowSpotPrices();
spotPrices.fetch({
success: function (model) {
console.log("New spotPrices model fetch: " + model.get('wti'));
},
failure: function (model) {
console.log("Failed to fetch spotPrices model");
}
});
var spotPricesView = new ShowSpotPricesView({model: spotPrices});
console.log("After spotPricesView.render: " + spotPricesView.model.get('wti'));
我可以使用API端点成功获取wti
值。
但是,我无法使用jQuery更新#OilSpotPrice
。我尝试使用固定字符串值进行更新,并使用model.get()
。
答案 0 :(得分:1)
使用.val()
jQuery function设置#OilSpotPrice
输入的值,而不是内部HTML。
this.$("#OilSpotPrice").val(this.model.get('wti'));
此外,您可以在find
方法中限制为一个jQuery initialize
调用。
initialize: function() {
// cache the jQuery object of the input once
this.$oilSpotPrice = this.$("#OilSpotPrice");
this.listenTo(this.model, 'sync change', this.render);
this.model.fetch();
this.render();
},
render : function() {
// then use the object
this.$oilSpotPrice.val(this.model.get('wti'));
return this;
}