Backbone.js中如何向SingleTodo视图传数据?代码为何未达预期?
Backbone.js视图无法同步模型数据的问题解决
我尝试在Backbone.js中向SingleTodo视图传递数据,但传递未成功,实际输出与预期不符。
代码示例
temp.html
<h1>This is Temp</h1> <div id="app"></div> <script type="text/template" id="app-template"> Title: <%= title %><br/> isCompleted: <%= isCompleted %> </script>
temp.js
const SingleTodo = Backbone.Model.extend({ defaults: { title: "", isCompleted: false } }); const TodoView = Backbone.View.extend({ el: "#app", template: _.template($("#app-template").html()), initialize: function () { this.model = new SingleTodo(); this.render(); }, render: function () { this.$el.html(this.template(this.model.toJSON())); return this; } }); $(document).ready(function () { const todoView = new TodoView(); todoView.model.set({ title: "A simple to-do", isCompleted: true }); });
输出对比
预期输出:

实际输出:

问题原因
视图初始化时调用了render()渲染了模型的默认数据,但后续修改模型数据时,Backbone不会自动将数据变化同步到视图,所以页面仍显示初始的默认值。
解决方法
方法一:监听模型change事件自动重渲染
在视图的initialize方法中添加模型事件监听,当数据变化时自动触发渲染:
const TodoView = Backbone.View.extend({ el: "#app", template: _.template($("#app-template").html()), initialize: function () { this.model = new SingleTodo(); // 监听模型change事件,数据更新时自动调用render this.listenTo(this.model, "change", this.render); this.render(); }, render: function () { this.$el.html(this.template(this.model.toJSON())); return this; } });
方法二:修改数据后手动调用render
如果不需要自动监听,可在修改模型数据后手动触发视图渲染:
$(document).ready(function () { const todoView = new TodoView(); todoView.model.set({ title: "A simple to-do", isCompleted: true }); // 手动调用render更新视图 todoView.render(); });
修复后效果
页面将正确显示:
Title: A simple to-do isCompleted: true
内容的提问来源于stack exchange,提问作者Deepanshu Yadav
相关产品推荐
相关产品推荐

