Marcin
Marcin

Reputation: 352

Model not updating on form submit, using Backbone + Stickit

I'm trying to use the backbone.stickit library to bind my form input to the model but can't seem to get the model to update correctly.

The keyup event appears to work correctly, i can see the value change if i use the "onSet" callback to display it:

    bindings: {
        '#firstName': {
            observe: 'firstName',
            onSet: function(val, options) {
                $('#output').html(val);
            }
        }
    }

Here is my code (Run it on jsfiddle):

HTML

<div id="view">
    <form name="form" id="form">
        <input id="firstName" type="text"/>
        <input type="submit" id="submit"/>
    </form>
    <div id="output"></div>
</div>  

JavaScript

var app = {

    Model: Backbone.Model.extend({
        firstName: 'test'
    }),

    View: Backbone.View.extend({
        el: "#view",

        initialize: function(){ 
            this.model = new app.Model();
            this.render(); 
        }, 
        bindings: {
            '#firstName': 'firstName'
        },        
        render: function(){ 
            this.$el.html( this.template ); 
            this.stickit();
        }, 
        events: {
            "submit #form": "submitForm"
        },

        submitForm: function(e) {
            e.preventDefault();
            $('#output').html('output:'+this.model.firstName);
        }

    })
};

var view = new app.View();

Upvotes: 0

Views: 298

Answers (1)

MorKadosh
MorKadosh

Reputation: 6006

The way of getting a model attribute is usally not by accessing the attribute name as an object property, the way you did it this.model.firstName. personally I know a very few cases of such implemntation. The so called right way to do that is by using get method: this.model.get("firstName"). This will return the current model value.

I usually define getters and setters for each model I use, so I would do the following:

getFirstName: function(){
    return this.get("firstName");
}

Just looks better and more "easy on the eyes" :) (but totally not a must)

Here's an update of your fiddle: http://jsfiddle.net/srhfvs8h/1/

Upvotes: 0

Related Questions