简体   繁体   English

向javascript对象添加行为

[英]adding behavior to javascript objects in angular

I am new to using angular and had a question regarding adding behavior to objects in angular. 我是刚开始使用angular的人,并且对将行为添加到angular中的对象有疑问。

I have a case in which I have getting an object / or array of objects say person using $http 我有一种情况,我得到一个对象或对象数组说使用$http

var person =
    {
      id : 123,
      firstname : "james",
      lastname : "bond",
      username : "james00",
      profileGuid : "DSKFSJKFBSFBJBSFKJBAKBDS",
      projects : [
             {
                id : 1,
                name : "gold finger"
             }
       ] 
    }

I want to add behavior like say 我想添加类似的行为

 var spyBehavior = 
 {
    greet : function(){
        return this.lastname + " " + this.firstName + " " + this.lastName;
    },

    hasExperience : function(){
      this.projects && this.projects.length && this.projects.length > 0
    }
 }

Currently I do this with angular.extend(person, spyBehavior) 目前,我使用angular.extend(person, spyBehavior)

  • What is the pros/cons of adding behavior using such spyBehavior object? 使用此类spyBehavior对象添加行为的利弊是什么?
  • Should this be defined as an angular service ? 应该将其定义为有角度的服务吗? - in which case, I loose the reference of this -在这种情况下,我会放弃this的引用
  • Should this be outside angular world and exist as a simple javascript object which wraps around $http output ? 这是否应该在有角度的世界之外,并作为一个简单的JavaScript对象存在,该对象将$ http输出包装起来? how do I do it? 我该怎么做?

I think what you want is some kind of model. 我认为您想要的是某种模型。 I always define my models the following way as a factory, because services are singletons. 因为服务是单例的,所以我总是以以下方式将模型定义为工厂。

angular.module('myApp').factory('User', function() {
  var _greet = function() {
    console.log("hello");
  };
  var User = function(data) {
    angular.extend(this, {
      email: null,
      name: null
      greet: _greet
    }, data);
  };
  return User;
});

Then, you can inject your User "model" in any module you want. 然后,您可以在所需的任何模块中注入用户“模型”。 If you want to get a new instance of that model, just do a 如果要获取该模型的新实例,只需执行

var user = new User(data);

Following a single responsibility approach, this object is kinda stupid. 遵循单一责任方法,此对象有点愚蠢。 It only knows it's own properties, what to do with them and so on. 它只知道它是自己的属性,如何处理它们等等。 If you want to add some behaviour like updating this object through $http , just inject the $http service into your User model and do the stuff you want. 如果要添加一些行为,例如通过$http更新此对象,只需将$http服务注入到User模型中,然后执行所需的操作即可。 Just be sure, not to create unnecessary dependencies with other models. 只要确定,不要与其他模型建立不必要的依赖关系。

I use to define a prototype object in a Factory provider: 我用来在Factory提供程序中定义原型对象:

angular.module('MyApp').factory('SpyBehaviour', function(){
    var SpyBehaviour = {
        greet : function(){
            return this.lastname + " " + this.firstName + " " + this.lastName;
        },

        hasExperience : function(){
            this.projects && this.projects.length && this.projects.length > 0
        }
    };

    return SpyBehaviour;
});

Then, I create a new object with my prototype and extend it with the results from the $http service. 然后,用原型创建一个新对象,并使用$ http服务的结果对其进行扩展。 If you use the transformResponse function , then the $http promise will be resolved with your extended objects. 如果使用transformResponse函数 ,则$http Promise将与扩展对象一起解决。

$http.({
    method: 'GET',
    url: '/persons',
    transformResponse: function (data) {
        var persons = JSON.parse(data);

        return persons.map(function (person) {
            return angular.extend(
                Object.create(SpyBehaviour),
                person
            );
        });
    }
});

If you are retrieving your models from an HTTP backend, AngularJS has a cool feature called transformResponse . 如果要从HTTP后端检索模型,则AngularJS具有一个很酷的功能,称为transformResponse You can specify a transformResponse function for specific $http calls. 您可以为特定的$http调用指定transformResponse函数。 The function will receive as an argument the response from the http request, manipulate it according to your implementation, and then return it. 该函数将接收来自http请求的响应作为参数,根据您的实现对其进行操作,然后将其返回。 Of course, since angular $resource s are built on top of $http , you can use transformResponse in both. 当然,由于angular $resource是建立在$http之上的,因此您可以在两者中使用transformResponse

In short, if you want to receive an array of people and decorate it with some functionalities, this is what I would do: 简而言之,如果您想接待一群人并用一些功能来装饰它,这就是我要做的:

  • Implement a People $resource that maps to your API; 实现映射到您的API的People $resource
  • Implement a function that, given an array of people, adds the desired behavior. 实现一个功能,给定一系列人员,即可添加所需的行为。
  • Specify the aforementioned function as the transformResponse parameter of the People resource. 将上述功能指定为人员资源的transformResponse参数。

And you are done. 您完成了。 What you will get at the end of your request is an array of people with the additional functions. 在请求结束时您将得到一系列具有附加功能的人员。 You can do exactly the same with a simple $http request, the transformResponse attribute can be specified in the same way. 您可以使用简单的$http请求执行完全相同的操作,可以用相同的方式指定transformResponse属性。

See also this short egghead.io tutorial . 另请参阅此简短的egghead.io教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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