Jeremy
Jeremy

Reputation: 3538

dojo 1.9: what annotation does declare.safeMixin add?

I have been reading through the dojo 1.9 documentation about declare.safeMixin(), focusing on the difference between it and lang.mixin.

Here is the explanation I found...

safeMixin() is a function defined in dojo/declare. It has the same functionality as dojo/_base/lang::mixin(), but additionally it annotates all copied methods compatibly with dojo/declare. This decoration can affect how this.inherited() works in mixed-in methods.

I can follow the example but it doesn't really explain exactly what is added and where, can anyone give any further examples of what annotation is added to each copied method?

So to be clear, I'm not asking for an explanation of inheritance, I'm just asking specifically about the annotations added by using declare.safeMixin() instead of lang.mixin.

Upvotes: 2

Views: 966

Answers (2)

C Snover
C Snover

Reputation: 18826

safeMixin adds the nom property to functions that are mixed in to the target. This property is set to the key from the source object that the function was assigned to. e.g. if you call declare.safeMixin(target, { foo: function() {} }), the nom property for that function is "foo". This is necessary for this.inherited(arguments) to automatically figure out that it should call the parent "foo". The alternative to using safeMixin would be to explicitly specify the name of the parent function: this.inherited('foo', arguments);.

Upvotes: 2

Ken Franqueiro
Ken Franqueiro

Reputation: 10559

Using safeMixin allows you to mix functions into an instance that can take advantage of this.inherited the same way that prototype methods defined using declare can.

For example, the following will log 2 messages:

require([
    "dojo/_base/lang",
    "dojo/_base/declare"
], function(lang, declare){
    var A = declare(null, {
        method: function () {
            console.log('method in prototype');
        }
    });
    var a = new A();

    declare.safeMixin(a, {
        method: function () {
            this.inherited(arguments);
            console.log('method in instance');
        }
    });

    a.method();
});

Without safeMixin, you wouldn't be able to call this.inherited(arguments) from the overriding method (at least, not without additional parameters) - you'd end up getting an error:

Error: declare: can't deduce a name to call inherited()

Upvotes: 4

Related Questions