[英]Backbone bind Model to View
我目前正在學習如何處理backbone.js。 目前我遇到的問題是,當視圖通過用戶輸入時,模型不會更新。
當我更改textarea的輸入並單擊按鈕時,我發送舊數據,因為視圖沒有通知模型發生了更改。
我做錯了什么?
define([
'jquery',
'underscore',
'backbone',
'postModel'
], function($, _, Backbone, PostModel){
var PostView = Backbone.View.extend({
timer: null,
el: $('.admin__wrapper'),
template: $('#post_template'),
initialize: function () {
console.log('Initializing Post View');
this.model = new PostModel({id: this.id});
this.listenTo(this.model, 'change', this.render);
this.model.fetch();
},
events: {
'keyup textarea': 'keyup',
'click button': 'submit'
},
submit: function(event) {
this.model.save();
},
render: function(){
var template = _.template(this.template.html(), { post: this.model });
this.$el.html(template);
return this;
}
});
return PostView;
});
<script type="text/template" id="post_template">
<div class="post__title">
<div class="entry">
<input class="input--less" name="title" type="text" value="<%= post.get('title') %>" placeholder="Post title">
</div>
</div>
<div class="entry post__panel post__markdown">
<header class="entry__header post__panel__header">
<span><small>markdown</small></span>
</header>
<div class="post__boundary">
<textarea name="content" id="editor" class="input--less post__editor" rows="5"><%= post.get('content') %></textarea>
</div>
</div>
<div class="entry post__panel post__html">
<header class="entry__header post__panel__header">
<span><small>preview</small></span>
<span id="reading-time" class="float--right" style="text-align: right"></span>
</header>
<div class="post__boundary">
<div class="post__preview" id="preview"><%= post.get('content_compiled') %></div>
</div>
</div>
<div class="post__footer">
<span class="batch--tag-4 post__icon"></span>
<button class="button button--blue post__button">Publish</button>
<a href="#?" class="batch--settings-2 post__settings post__icon"></a>
</div>
</script>
當用戶點擊提交你沒有從視圖中獲取數據時,你只是使用默認值保存模型,因此不會觸發任何更改事件,你必須在keyup
方法中執行類似這樣的事情,這是由keyup event
觸發的。
keyup: function(e)
{
this.model.set(e.target.name, e.target.value, {silent: true});
}
假設您正確命名了textarea,將更新正確的模型屬性。 所以現在當通過submit
調用this.model.save
時,這些屬性將被保存,觸發change事件並重新呈現視圖。
當您更改頁面中的表單時,此更改不會自動在模型中設置,您必須自己設置。
Backbone不像Angular Js那樣提供雙向數據綁定,您需要自己設置模型然后同步模型。
嘗試使用Backbone Mutators在Bakcbone中進行雙向數據綁定。 另外作為后續閱讀本文
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.