Using Backbone models with AngularJS

后端 未结 7 1550
攒了一身酷
攒了一身酷 2021-01-30 02:11

Recently I was thinking about the differences and similarities between Backbone.js and AngularJS.

What I find really convenient in Backbone are the Backbone-Models and t

相关标签:
7条回答
  • 2021-01-30 03:06

    I was wondering if anyone had done this too. In my most recent / first angular app, I found Angular to be pretty lacking in models and collections (unless I am missing something of course!). Sure you can pull data from the server using $http or $resource, but what if you want to add custom methods/properties to your models or collections. For example, say you have a collections of cars, and you want to calculate the total cost. Something like this:

    With a Backbone Collection, this would be pretty easy to implement:

    carCollection.getTotalCost()
    

    But in Angular, you'd probably have to wrap your custom method in a service and pass your collection to it, like this:

    carCollectionService.getTotalCost(carCollection)
    

    I like the Backbone approach because it reads cleaner in my opinion. Getting the 2 way data binding is tricky though. Check out this JSBin example.

    http://jsbin.com/ovowav/1/edit

    When you edit the numbers, collection.totalCost wont update because the car.cost properties are not getting set via model.set().

    Instead, I basically used my own constructors/"classes" for models and collections, copied a subset of Backbone's API from Backbone.Model and Backbone.Collection, and modified my custom constructors/classes so that it would work with Angular's data binding.

    0 讨论(0)
提交回复
热议问题