3

I'm trying to create a invoice rows list with backbone and one of the buttons/events is that when You click "add" on an existing row, it should add a new row right below the one that's "add" button was clicked.

First, I am not sure if I should handle this event in the InvoiceItemView or InvoiceItemListView, and second, I am not sure how to do this. Can anybody help me?

I tried this:

$(function(){

// Invoice row
var InvoiceItem = Backbone.Model.extend({

    // Set default values
    defaults : {
        name: "",
        quantity: 1,
        price: "",
        total: ""
    },

    // Ensure each item has at least a quantity of one
    initialize: function() {
        this.set({ "quantity" : this.defaults.quantity });
    },

    // Delete item (row) from invoice
    clear: function() {
        this.destroy();
    }        

});

// Collection of Invoice Items ( rows )
var InvoiceItemList = Backbone.Collection.extend({

    // Colelction's model
    model: InvoiceItem,

    // Use localStorage to save data
    localStorage: new Store("invoices-backbone"),

    // Calculate invoice totals
    calculate_totals: function() {
        alert('arvutus');  
    },

    // Generate next item order number
    nextOrder: function() {
        if (!this.length) return 1;
        return this.last().get('order') + 1;
    }

});

// Create a global colelction of Invoice Rows
var InvoiceItems = new InvoiceItemList;

// Invoice Item View
var InvoiceItemView = Backbone.View.extend({

    // it's a tr tag
    tagName: 'tr',

    // Cache the template
    template: _.template($('#invoiceitem-template').html()),

    events: {
        "click .remove"     : "clear",
        "click .add"        : "addAfter"
    },

    initialize: function() {
        _.bindAll(this, 'render', 'addAfter', 'remove');
        this.model.bind('change', this.render);
        this.model.bind('destroy', this.remove);
        this.render();
    },

    // Render the contents
    render: function() {
        $(this.el).html(this.template(this.model.toJSON()));
        $(this.el).attr('id', 'item-' + this.model.get('order'));
        return this;
    },

    // Remove and destroy the item
    clear: function() {
        this.model.clear();
    },

    // Add new item
    addAfter: function(ItemId) {
        var view = new InvoiceItemView({model: InvoiceItem});
        this.$("tbody tr#item"+ItemId).after(view.render().el);
    }

});

// Invoice Item List View
InvoiceItemListView = Backbone.View.extend({

    // Bind to existing DOM element
    el: $("#items"),

    // Template for displaying totals
    totalsTemplate: _.template($('#totals-template').html()),

    // Kick-off (load from localStorage as well)
    initialize: function() {
        _.bindAll(this, 'addOne', 'render');

        InvoiceItems.bind('add', this.addOne);

        InvoiceItems.fetch();

        InvoiceItems.create(this.newAttributes());
        InvoiceItems.create(this.newAttributes());
        InvoiceItems.create(this.newAttributes());

        this.render();
    },

    // Re-render the totals
    render: function() {
        this.$('#totals').html(this.totalsTemplate({
            total: this.total
        }));
    },

    // Generate the attributes for a new Invoice Item.
    newAttributes: function() {
        return {
            name: '',
            price: '',
            total: '',
            order: InvoiceItems.nextOrder()
        };
    },

    // Add a single invoice item to the list
    addOne: function(InvoiceItem) {
        var view = new InvoiceItemView({model: InvoiceItem});
        this.$("tbody").append(view.render().el);
    }

});

var iView = new InvoiceItemListView;

});

But I am getting an error: this.model.toJSON is not a function

2
  • 2
    will need to see more code, we can't really help out with the error without more code. for example, {model: InvoiceItem} where does the InvoiceItem come from? it's not an argument of that function, it's not visible in your given code example, maybe thats the error, but then again i can't say because i don't know more about the code
    – Sander
    Jan 8, 2012 at 0:24
  • Sander, I've added my full code now
    – ragulka
    Jan 8, 2012 at 7:52

1 Answer 1

5

The problem is where you create your new InvoiceItemView. You have to create a new instance of InvoiceItem

// Add new item
addAfter: function(ItemId) {
    var view = new InvoiceItemView({model: new InvoiceItem()});
    this.$("tbody tr#item"+ItemId).after(view.render().el);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.