I'm currently learning how to deal with backbone.js. Currently I have the problem that the model isnt updating when the view does through user input.
When I change the input of the textarea and I click the button, I send the old data since the view didnt notify the model that a change happened.
What do I do wrong?
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>
When the user clicks submit your not getting the data from the view you are simply saving the model with defaults, therefor not firing any change events, you will have to do something like this in keyup
method which is triggered by the keyup event
.
keyup: function(e)
{
this.model.set(e.target.name, e.target.value, {silent: true});
}
Assuming you correctly named your textarea, the correct model attribute will be updated. So now when this.model.save
is called by submit
these attributes will be saved triggering the change event and re-rendering the view.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments