简体   繁体   中英

Use $.get() or this.model.save() (Backbone.js)

I have a list of images each with a 'Like' button. When the 'Like' button is clicked, an AJAX request (containing the item_id and user_id ) will be sent to the serverside to record the Like (by adding a new row in the table likes with values for item_id and user_id ).

The model Photo is used for the images displayed on the page. If I understand correctly, this.model.save() is used if I want to update/add a new Photo , so it is not suitable for recording 'Likes'. Therefore, I have to use something like $.get() or $.post() . Is this the conventional way?

Or do I create a new model called Like as shown below, which seems to make it messier to have a View and template just for a Like button.

Like = Backbone.Model.extend({
    url: 'likes'
});

LikeView = Backbone.View.extend({

    template: _.template( $('#tpl-like').html() ),

    events: {
        'click .btn_like': 'like'
    },

    like: function() {
        this.model.save({
            user_id: 1234,
            post_id: 10000
        })
    }
});

In similar cases to this I've used the $.get method rather than create a new model, obviously this will depend on your application, but here are my reasons.

This case appears to have the following characteristics:

  1. Like is a relationship between a person and a photo,
  2. you seem to have a server side resource that accepts the photo and user ids to create this relationship already,
  3. you probably have no other information attached to that relationship, and
  4. you probably don't have significant view logic to go with the like itself

This is better handled by adding another attribute to your Photo object, that contains the number of likes. Then use $.get to create the like , and a 200 response will simply update the photo object to up it's count (and hence the view). Then the server side just needs to include the like count as part of it when it returns.

I'm assuming here that once a like is made you won't be updating it. If you do need to update or delete it, I might still keep using the $.get . You can add a likes array to your photo object where each element is the id of the like resource. The view will display the length of the array as the count, and if you need to delete the like, you have access to the id and you can use $.post . Just make sure you don't use .push to add values to your array since that'll bypass backbone's set method and you won't get your event callbacks. You need to clone the array, then push, and then set it when you make changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM