how to update model is part of a collection

ahmedsaber111

My application uses backbone.js and requirejs, I have a "Questions module, that displays questions from database and its answers" and below are the structure of the module:

  1. views/questions view
  2. views/question item view
  3. collection/questions collection
  4. models/question model

everything is going ok with my app as i could retrieve all the data from the collection and render it to the page. earlier this week i was stacked with an issue when creating my rating system that consist of up and down buttons,

what i need to do is to update the model when the user clicking on the up/ down button with the new value and re-render the item view again with the new value.

I'll attach for you the code of the four pages mentioned above, everything on the codes below are working perfectly and i didn't include any functions or events that should handle the update procedure.

Questions view

// Filename: views/_activity_slider_inHeader
define([
'jquery',
'underscore',
'backbone',
'app/config',
'app/collections/questions',
'app/views/home_question_item',
'text!templates/questions_home.html',
'bootbox'
], function($, _, Backbone, Config, QuestionsCollection, SingleQuestionView, question_slider_template, bootbox) {
var ActivitySlider = Backbone.View.extend({
    el: $(".content_container"),
    template: _.template(question_slider_template),
    initialize: function() {
        /*
         * initial script
         */
        var questionsCollection = new QuestionsCollection();
        this.collection = questionsCollection;
        questionsCollection.fetch({
            reset: true,
            error: function(model, xhr, options) {
                /*
                 * When triggering error:
                 *      1. If ther response is not valid json
                 *      2. There is error connecting to the server
                 */
                if (xhr['readyState'] === 1 | xhr['status'] === 404) {

                    /*
                     * the connection has not been made, user may be not connected to the internet
                     * @readyState The state of the request:
                     *             0 = UNSENT
                     *             1 = OPENED
                     *             2 = HEADERS_RECEIVED
                     *             3 = LOADING
                     *             4 = DONE
                     */
                    var msg = "pla pla",
                            title = "pla pla";

                    bootbox.dialog({
                        /*
                         * bootbox.dialog, bootbox.prompt, bootbox.confirm, bootbox.alert
                         * bootbox should have a callback used for the buttons
                         */
                        message: msg,
                        title: title,
                        buttons: {
                            main: {
                                label: "pla pla",
                                className: "",
                                callback: function() {

                                }
                            }
                        }
                    });

                }
                if (xhr['readyState'] === 4 & xhr['status'] === 200) {
                    /*
                     * Handling empty data
                     * connections to the server made successfully but seems to be there is no data returned by the server
                     */

                }
            }
        });
        this.listenTo(this.collection, 'reset', this.render);
        this.renderList();
    },
    render: function(questions) {

        /*
         * Ilterate through all activities and start rendering item by item through the SingleActivityView
         */
        if (questions.size() === 0) {
            /*
             * there is no available activities
             * further use ..
             */

        } else {

            var i = 1;
            //there is activities available
            questions.each(function(question) {
                //create instance of the single item view
                var current = question.attributes,
                        singleQuestionView = new SingleQuestionView({
                    model: question,
                    collection: this.collection,
                    id: i
                });
                this.$el.append(singleQuestionView.render().el);

                i++;
            }, this);

        }

    },
    renderList: function() {
        /*
         * rendering the slider structure itself first
         */
        var data = {
            path: Config.baseUrl,
            _: _
        };
        this.$el.append(this.template(data));
    }
});

return ActivitySlider;

});

Question item view

/* Filename: views/home_question_item
* used to handle one row of the questions objects, merge the model data onto call list item
*/
define([
'jquery',
'underscore',
'backbone',
'app/config',
'text!templates/question_item_home.html',
'string',
'moment',
'moment_ar',
'jquerycookie',
'purl'
], function($, _, Backbone, Config, QuestionItemTemplate, S, moment, moment_ar) {
var url = $.url(),
    ActivityItemView = Backbone.View.extend({
    el: $("li"),
    template: _.template(QuestionItemTemplate),
    initialize: function(){

    },
    render: function() {

        var model = this.model.attributes;

        var data = {
            path: Config.baseUrl,
            lang: url.segment(1),
            id: model['id'],
            date: model['date'],
            views: model['views'],
            author: model['author'],
            authorName: model['authorName'],
            question: model['question'],
            answer: model['answer'],
            rate: model['rate'],
            _ : _,
            S: S,
            moment: moment
        };

        $(".list_of_question").append(this.template(data));
        return this;
    },
    close: function(){
        console.log('destroyed');
        $(this.el).unbind();
        $(this.el).remove();            
    }
});
return ActivityItemView;
});

Questions collection

// Filename: collections/activities
define([
'jquery',
'underscore',
'backbone',
'app/config',
'app/models/question',    
'moment',
'purl'
], function ($, _, Backbone, Config, question, moment) {

var url = $.url(),
    ActivitiesCollection = Backbone.Collection.extend({

    model: question,
    url: Config.baseUrl + url.segment(1) + '/pull/questions'

});
return ActivitiesCollection;
});

Questions model

// Filename: models/activity
define([
'jquery',
'underscore',
'backbone',
'app/config',
'purl'
], function ($, _, Backbone, Config) {

var url = $.url(),
    ActivityModel = Backbone.Model.extend({
    defaults: {
        id: 'N/A'
    },
    urlRoot: Config.baseUrl + url.segment(1) + '/pull/questions/'

});
return ActivityModel;

});
Puigcerber

I haven't tested the code but it should be something like this:

var ActivityItemView = Backbone.View.extend({
    el: $("li"),
    template: _.template(QuestionItemTemplate),
    initialize: function(options){
        this.model = options.model;
        this.listenTo(this.model, 'change', this.render, this); 
    },
    events : {
        'click #arrowUp' : 'increaseModelRating',
        'click #arrowDown' : 'decreaseModelRating',
    },
    render: function() {
        var data = { '...' };
        $(".list_of_question").append(this.template(data));
        return this;
    },
    increaseModelRating: function() {
        var currentRating = this.model.get('rating');
        this.model.set('rating', ++currentRating);
    },
    decreaseModelRating: function() {
        var currentRating = this.model.get('rating');
        this.model.set('rating', --currentRating);
    },  
    close: function() { '...' }
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Update a Model and a Collection of Models on a Single View (MVC4)

From Dev

AngularJS how to change part of a model

From Dev

How to update a collection based on another collection in MongoDB?

From Dev

How to update jtable model correctly?

From Dev

Update entity that is not part of the client collection

From Dev

How to update dynamically a model in Django?

From Dev

AngularJS how to dynamically update part of scope with variable

From Dev

How to update CATIA part in vba?

From Dev

How to update the TTL on a collection?

From Dev

How to update without the last part of a string

From Dev

how to insert part of model properties in mvc 5

From Dev

How to update and replace part of old data

From Dev

Django - Use model fields part in a create or update query

From Dev

Django - Use model fields part in a create or update query

From Dev

How to update part of a file atomically?

From Dev

Update entity that is not part of the client collection

From Dev

How to update the TTL on a collection?

From Dev

How to update model and view model in MVVM pattern?

From Dev

Bind a collection of a model to only a part of another collection

From Dev

Marionette: setting collection after render doesn't update on model add

From Dev

How to update a model with Sails JS

From Dev

How to update part of a template when a collection is updated?

From Dev

How to update relation of a model in Phoenix?

From Dev

How to update model in DataSource window?

From Dev

Angular 2 - how to update model

From Dev

How to update collection in pymongo

From Dev

How to update a listview from viewmodel binded model observable collection to itemsource

From Dev

How to update section in the Mongo collection?

From Dev

Mongoose How to update nested model?

Related Related

  1. 1

    Update a Model and a Collection of Models on a Single View (MVC4)

  2. 2

    AngularJS how to change part of a model

  3. 3

    How to update a collection based on another collection in MongoDB?

  4. 4

    How to update jtable model correctly?

  5. 5

    Update entity that is not part of the client collection

  6. 6

    How to update dynamically a model in Django?

  7. 7

    AngularJS how to dynamically update part of scope with variable

  8. 8

    How to update CATIA part in vba?

  9. 9

    How to update the TTL on a collection?

  10. 10

    How to update without the last part of a string

  11. 11

    how to insert part of model properties in mvc 5

  12. 12

    How to update and replace part of old data

  13. 13

    Django - Use model fields part in a create or update query

  14. 14

    Django - Use model fields part in a create or update query

  15. 15

    How to update part of a file atomically?

  16. 16

    Update entity that is not part of the client collection

  17. 17

    How to update the TTL on a collection?

  18. 18

    How to update model and view model in MVVM pattern?

  19. 19

    Bind a collection of a model to only a part of another collection

  20. 20

    Marionette: setting collection after render doesn't update on model add

  21. 21

    How to update a model with Sails JS

  22. 22

    How to update part of a template when a collection is updated?

  23. 23

    How to update relation of a model in Phoenix?

  24. 24

    How to update model in DataSource window?

  25. 25

    Angular 2 - how to update model

  26. 26

    How to update collection in pymongo

  27. 27

    How to update a listview from viewmodel binded model observable collection to itemsource

  28. 28

    How to update section in the Mongo collection?

  29. 29

    Mongoose How to update nested model?

HotTag

Archive