我正在尝试以纯粹的方式构建应用程序。这是设置模型和渲染 View 的正确方法吗?
最新的 fiddle https://jsfiddle.net/g48ckukd/19/
var UserBankModel = Backbone.Model.extend({
defaults: {
chips: 100
},
initialize: function() {
console.log("UserBankModel initialize");
this.on("change:chips", function(model) {
var chips = model.get("chips"); // 23232
console.log("Changed my chips to " + chips);
});
}
});
var UserBankView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
this.$el.html(userBankModel.get("chips"));
}
});
//user bank model initialize with default 100 chips
var userBankModel = new UserBankModel();
//won or lost chips -- set new chip value
userBankModel.set({
chips: 1001
});
var userBankView = new UserBankView({
el: $("#bankvalue")
});
userBankView.render();
最佳答案
您已经在模型和 View 之间建立了良好的关系。我要说的一件事是,您很快就会厌倦现有的模板化方式:
bank value test <div id="bankvalue">2</div>
在你的标记中,然后在你的 View 中选择一个 DOM 对象并在你的渲染函数中设置 html:
render: function() {
this.$el.html(userBankModel.get("chips"));
}
以这种方式构建应用程序将会很困难。您可能想开始使用一些客户端模板来简化您的生活。像 mustache 之类的东西。一旦您使用许多键模板化模型或模板化模型列表,这将开始有用。这是一篇文章,展示了一个带有主干的示例:https://gist.github.com/kyleondata/3440492
关于javascript - Backbone js 模型/ View 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35532389/