这是 router 中的一个函数。routes: { "post/:id": "postEdit"},postEdit: function (id) { console.log('router.js, got router: #/post/' + id);
UILoading($("#main")); var model = new PostModel({_id: id});
model.fetch({ success: function () { new PostEditView({model: model});
}, error: function () { console.log("failed, on router: #/post/" + model.id);
}
});
}接下来是 View 的代码var PostEditView = Backbone.View.extend({
el: '#main',
template: doT.template(PostEditTemplate),
events: { 'click #savePost': 'save'
},
initialize: function () {
_.bindAll(this, 'render'); this.model.bind("change", this.render, this); var converter = Markdown.getSanitizingConverter(); this.editor = new Markdown.Editor(converter); this.render();
},
render: function () { this.$el.html(this.template(this.model.toJSON())); this.editor.run();
},
save: function () { this.model.set({
title: $("#post_title").val(),
slug: $("#post_slug").val(),
created: $("#post_created").val(),
tags: $("#post_tags").val().split(','),
content: $(".post_content").val()
}); this.model.save();
}
});最后发现,当访问过多次#/post/5103fbb3817feb1c10000001,/#/post/5103c114ce4c724c12000002 后,save 这个函数会重复调用。
2 回答
慕工程0101907
TA贡献1887条经验 获得超5个赞
routes: { "post/:id": "postEdit"},postEdit: function (id) { console.log('router.js, got router: #/post/' + id); UILoading($("#main")); var model = new PostModel({_id: id}); var view = new PostEditView({model: model}); model.fetch({ error: function () { console.log("failed, on router: #/post/" + model.id); } }); }
view 里的initialize可以不直接执行render,放到事件里吧
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
view 的切换,主要由路由来触发,所以在 router 中加了一个函数来做 view 切换管理。
switchView: function (view) { if (this.currentView) { this.currentView.remove(); } this.currentView = view; },
每次 route ,都调用 switchview 来进行切换。
// #/post/512c4527f7d8797818000001postEdit: function (id) { console.log('router.js, got router: #/post/' + id); var that = this; var model = new PostModel({_id: id}); var view = new PostEditView({model: model}); this.switchView(view); //...... do something. }
添加回答
举报
0/150
提交
取消