1

Я новичок в магистрали, я следую учебному курсу, и я пытаюсь использовать локальное хранилище в качестве базы данных, но мне не удалось найти статью, в которой объясняется, как использовать их вместе ,Местное хранилище магистральной сети

Это код:

$(function() { 
window.app = { 
    Models: {}, 
    Collections: {}, 
    Views: {} 
}; 

window.template = function(id) { 
    return _.template($('#' + id).html()); 
} 

//Item model 
app.Models.Item = Backbone.Model.extend({ 
    defaults: { 
     title: '' 
    } 
}); 




//items collection 
app.Collections.ItemsList = Backbone.Collection.extend({ 
    // reference to the model 
    model: app.Models.Item, 

    //save all items in local storage 
    localStorage: new Backbone.LocalStorage('items-store') 
}); 




//the items list 
app.Views.Items = Backbone.View.extend({ 
    tagName: 'ul', 

    initialize: function() { 
     this.collection.on('add', this.addOne, this); 
    }, 

    render: function() { 
     //for each element in the collection call the add one function 
     this.collection.each(this.addOne, this); 
     return this; 
    }, 

    addOne: function(itemModel) { 
     // create a new child view 
     var itemView = new app.Views.Item({model: itemModel}); 
     //append to the root element 
     this.$el.append(itemView.render().el); 
    } 
}); 




// one item view 
app.Views.Item = Backbone.View.extend({ 
    //tag name of the view 
    tagName: 'li', 

    template: template('itemTemplate'), 

    events: { 
     'click .edit': 'editModel' 
    }, 

    initialize: function() { 
     //rerender the model whet the text is changed 
     this.model.on('change', this.render, this); 
    }, 

    render: function() { 
     //render the template 
     var template = this.template(this.model.toJSON()); 
     //tale the list item and populate it with the associated model 
     this.$el.html(template); 
     return this; 
    }, 

    editModel: function() { 
     //prompt the user to change the text 
     var newValue = prompt('You want to change the text?', this.model.get('title')); 
     //if cancel is pressed 
     if(!newValue) { return}; 
     //add the new value to the model 
     this.model.set('title', newValue); 
    } 
}); 




//add new item view 
app.Views.AddItem = Backbone.View.extend({ 
    el: '#addItem', 

    collection: new app.Collections.ItemsList, 

    events: { 
     'submit' : 'submit' 
    }, 

    initialize: function() { 
     this.collection.fetch({reset: true}); 

     //call the Items view 
     var items = new app.Views.Items({collection: this.collection}); 
     //populate the itemsList with the ul 
     $('#itemsList').html(items.render().el); 

     //this is just for demo purpose 
     this.store(); 
    }, 

    submit: function(e) { 
     e.preventDefault(); 
     //get the value from the input 
     var newTaskTitle = this.$el.find('input[type=text]').val(); 
     //create a new model with the value from newTaskTitle 
     var item = new app.Models.Item({title: newTaskTitle}); 
     //create the collection in order to trigger the localstorage plugin 
     this.collection.create(item); 

     //this is just for demo purpose 
     this.store(); 
    }, 

    store: function() { 
     //this is just for demo purpose 
     //items in local storage 
     for(var i = 0; i < localStorage.length; i++) { 
      var obj = localStorage.getItem(localStorage.key(i)); 
      $('.number span').html(localStorage.length); 
      $('#localStorage').append('<div>' + i + '---' + obj + '</div>'); 

     } 

    } 
}); 

//dummy collection 
var itemsCollection = new app.Collections.ItemsList([ 
    { 
     title : 'go home' 
    }, 
    { 
     title : 'go home1' 
    }, 
    { 
     title : 'go home2' 
    } 
]); 

//call the view with the dummy collection 
// var addItems = new app.Views.AddItem({collection: itemsCollection}); 

// //call the view without the collection 
var addItems = new app.Views.AddItem(); 
//end of function 
}()); 

Edit: код был изменен, и jsfiddle обновление: http://jsfiddle.net/9z0cc6r8/1/

я узнал, что позвоночник LocalStorage плагин сохраняет модели в локальном хранилище браузера, как this: this.collection.create (item); но если я обновляю страницу, элементы перестают работать с colelction, и они снова не отображаются на странице.

Кто-нибудь знает, как я могу отображать свои объекты на странице из локального хранилища? Мне все еще нужно получить доступ к модели после этого, потому что я хочу выполнить редактирование и удаление действий на них.

P.S. Кажется, что на js скрипка это прекрасно работает. Но на местном он не чувствует.

+0

попробуйте использовать localstorage в одиночку, а затем попытайтесь использовать магистраль в одиночку, когда вы думаете, что вы хороши в обоих, а затем попытайтесь интегрировать. –

+0

Возможно, вы захотите [переопределить метод sync() вашей коллекции) (http://backbonejs.org/#Collection-sync). MDN о [Storage API] (https://developer.mozilla.org/en-US/docs/Web/API/Storage) –

ответ