Question

I'm trying to store my models into local storage using backone.localStorage. Unfortunately nothing gets stored.

As for as I understand the collection needs only one line

localStorage: new Backbone.LocalStorage("days")

but that doesn't help. If I check the localStorage using Chrome dev tools nothing is stored.

This is my code:

// Filename: app.js
define([
    'jquery',
    'underscore',
    'backbone',
    'localStorage'
], function($, _, Backbone){
    var initialize = function(){
        (function ($) {

            var Day = Backbone.Model.extend({
                initialize: function() {
                    this.on("change", this.calculateWorkTime);
                    this.calculateWorkTime();
                },
                defaults: {
                    "date":     new Date(),
                    "fromAm":   0,
                    "toAm":     0,
                    "fromPm":   0,
                    "toPm":     0,
                    "workTime": 0
                },
                isValidTime: function(n) {
                    return !isNaN(parseFloat(n)) && isFinite(n) && parseFloat(n)>0;
                },
                calculateWorkTime: function() {
                    var work = 0.0;
                    if (timeToFloat(this.get("fromAm")) < timeToFloat(this.get("toAm")) ) {
                        work += timeToFloat(this.get("toAm")) - timeToFloat(this.get("fromAm"));
                    }
                    if (timeToFloat(this.get("fromPm")) < timeToFloat(this.get("toPm")) ) {
                        work += timeToFloat(this.get("toPm")) - timeToFloat(this.get("fromPm"));
                    }
                    this.set("workTime", floatToTime(work));
                }
            });

            var DayList = Backbone.Collection.extend({
                model: Day,
                localStorage: new Backbone.LocalStorage("days")
            });

            var DataRow = Backbone.View.extend({
                tagName:  "tr",
                template: _.template($('#table-row-day').html()),
                events: {
                    "change .edit-field":  "updateModel",
                    "click #button-delete-day": "deleteDay"
                },
                initialize: function() {
                    this.listenTo(this.model, 'destroy', this.remove);
                },
                render: function() {
                    this.$el.html(this.template(this.model.toJSON()));
                    return this;
                },
                updateModel: function(event) {
                    var myValue = "leer";
                    switch (event.currentTarget.id) {
                        case "table-edit-date":
                            myValue = this.$('#table-edit-date').val();
                            this.model.set("date", myValue);
                            break;
                        case "table-edit-fromAm":
                            myValue = this.$('#table-edit-fromAm').val();
                            this.model.set("fromAm", myValue);
                            break;
                        case "table-edit-toAm":
                            myValue = this.$('#table-edit-toAm').val();
                            this.model.set("toAm", myValue);
                            break;
                        case "table-edit-fromPm":
                            myValue = this.$('#table-edit-fromPm').val();
                            this.model.set("fromPm", myValue);
                            break;
                        case "table-edit-toPm":
                            myValue = this.$('#table-edit-toPm').val();
                            this.model.set("toPm", myValue);
                            break;
                    }
                    this.render();
                    console.log(this.model.toJSON());
                },
                deleteDay: function(a, b, c, d) {
                    this.model.destroy();
                }
            });

            var Days = new DayList;

            AppView = Backbone.View.extend({
                el: $("body"),
                initialize: function () {
                    this.listenTo(Days, 'add', this.addOne);
                    this.listenTo(Days, 'all', this.refreshTotal);
                    this.total = this.$("#total-work");
                    Days.fetch();
                    this.refreshTotal();
                },
                events: {
                    "click #button-add-day":  "addDay"
                },
                addDay: function () {
                    var day = new Day({
                        "date":     $("#form-add-date").val(),
                        "fromAm":   $("#form-add-fromAm").val(),
                        "toAm":     $("#form-add-toAm").val(),
                        "fromPm":   $("#form-add-fromPm").val(),
                        "toPm":     $("#form-add-toPm").val()
                    });
                    Days.add(day);
                },
                addOne: function(day) {
                    var view = new DataRow({model: day});
                    this.$("#table-body-days").append(view.render().el);
                },
                refreshTotal: function() {
                    var work = 0;
                    Days.each(function($i) {
                        work += timeToFloat($i.get("workTime"));
                    });
                    this.total.html(floatToTime(work));
                }
            });

            function timeToFloat(time) {
                var parts = time.split(":");
                if (parts.length<2) return 0.0;
                return parseFloat(parts[0])+parseFloat(parts[1])/60;
            }

            function floatToTime(floatValue) {
                var fraction = floatValue - Math.floor(floatValue);
                var whole = Math.floor(floatValue);
                return whole+":"+Math.round(fraction*60.0);
            }


            var appview = new AppView;

        })($);
    };

    return {
        initialize: initialize
    };

});
Était-ce utile?

La solution

As the comment points out the calls to save are missing. I added them to DataRow.updateModel() and AppView.addDay().

This is the correct code:

// Filename: app.js
define([
    'jquery',
    'underscore',
    'backbone',
    'localStorage'
], function($, _, Backbone){
    var initialize = function(){
        (function ($) {

            var Day = Backbone.Model.extend({
                initialize: function() {
                    this.on("change", this.calculateWorkTime);
                    this.calculateWorkTime();
                },
                defaults: {
                    "date":     new Date(),
                    "fromAm":   0,
                    "toAm":     0,
                    "fromPm":   0,
                    "toPm":     0,
                    "workTime": 0
                },
                isValidTime: function(n) {
                    return !isNaN(parseFloat(n)) && isFinite(n) && parseFloat(n)>0;
                },
                calculateWorkTime: function() {
                    var work = 0.0;
                    if (timeToFloat(this.get("fromAm")) < timeToFloat(this.get("toAm")) ) {
                        work += timeToFloat(this.get("toAm")) - timeToFloat(this.get("fromAm"));
                    }
                    if (timeToFloat(this.get("fromPm")) < timeToFloat(this.get("toPm")) ) {
                        work += timeToFloat(this.get("toPm")) - timeToFloat(this.get("fromPm"));
                    }
                    this.set("workTime", floatToTime(work));
                }
            });

            var DayList = Backbone.Collection.extend({
                model: Day,
                localStorage: new Backbone.LocalStorage("days")
            });

            var DataRow = Backbone.View.extend({
                tagName:  "tr",
                template: _.template($('#table-row-day').html()),
                events: {
                    "change .edit-field":  "updateModel",
                    "click #button-delete-day": "deleteDay"
                },
                initialize: function() {
                    this.listenTo(this.model, 'destroy', this.remove);
                },
                render: function() {
                    this.$el.html(this.template(this.model.toJSON()));
                    return this;
                },
                updateModel: function(event) {
                    var myValue = "leer";
                    switch (event.currentTarget.id) {
                        case "table-edit-date":
                            myValue = this.$('#table-edit-date').val();
                            this.model.set("date", myValue);
                            break;
                        case "table-edit-fromAm":
                            myValue = this.$('#table-edit-fromAm').val();
                            this.model.set("fromAm", myValue);
                            break;
                        case "table-edit-toAm":
                            myValue = this.$('#table-edit-toAm').val();
                            this.model.set("toAm", myValue);
                            break;
                        case "table-edit-fromPm":
                            myValue = this.$('#table-edit-fromPm').val();
                            this.model.set("fromPm", myValue);
                            break;
                        case "table-edit-toPm":
                            myValue = this.$('#table-edit-toPm').val();
                            this.model.set("toPm", myValue);
                            break;
                    }
                    this.model.save();
                    this.render();
                    console.log(this.model.toJSON());
                },
                deleteDay: function(a, b, c, d) {
                    this.model.destroy();
                }
            });

            var Days = new DayList;

            AppView = Backbone.View.extend({
                el: $("body"),
                initialize: function () {
                    this.listenTo(Days, 'add', this.addOne);
                    this.listenTo(Days, 'all', this.refreshTotal);
                    this.total = this.$("#total-work");
                    Days.fetch();
                    this.refreshTotal();
                },
                events: {
                    "click #button-add-day":  "addDay"
                },
                addDay: function () {
                    var day = new Day({
                        "date":     $("#form-add-date").val(),
                        "fromAm":   $("#form-add-fromAm").val(),
                        "toAm":     $("#form-add-toAm").val(),
                        "fromPm":   $("#form-add-fromPm").val(),
                        "toPm":     $("#form-add-toPm").val()
                    });
                    Days.add(day);
                    day.save();
                },
                addOne: function(day) {
                    var view = new DataRow({model: day});
                    this.$("#table-body-days").append(view.render().el);
                },
                refreshTotal: function() {
                    var work = 0;
                    Days.each(function($i) {
                        work += timeToFloat($i.get("workTime"));
                    });
                    this.total.html(floatToTime(work));
                }
            });

            function timeToFloat(time) {
                var parts = time.split(":");
                if (parts.length<2) return 0.0;
                return parseFloat(parts[0])+parseFloat(parts[1])/60;
            }

            function floatToTime(floatValue) {
                var fraction = floatValue - Math.floor(floatValue);
                var whole = Math.floor(floatValue);
                return whole+":"+Math.round(fraction*60.0);
            }


            var appview = new AppView;

        })($);
    };

    return {
        initialize: initialize
    };

});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top