简体   繁体   中英

Referencing another function in array of functions

I'm using require.js and have a library of functions I use in multiple places. I define the functions thusly:

define(function (require) {

    "use strict";

    var $ = require('jquery');

    var UsefulFuncs = {};

    UsefulFuncs.hideAlert = function() {
        $('.alert').hide();
    };


    UsefulFuncs.loadURL = function (url){
            navigator.app.loadUrl(url, { openExternal:true });
            return false; 
    };


    UsefulFuncs.linkClicked = function (e) {    
        e.preventDefault();
        var url = $(e.currentTarget).attr("rel"); 
        this.loadURL(url);
    };


    return UsefulFuncs;

});

Then, in my backbone view, I call a function from the library with:

UsefulFuncs         = require('app/utils/useful_func'),

....

UsefulFuncs.linkClicked

This works fine for any standalone function in the library eg hideAlert(). However when one function in the library refers to another, such as linkClicked() calling loadURL(), I get an error:

Uncaught TypeError: Object [object Object] has no method 'loadURL'. 

Any ideas how I can reference loadUrl()?

Try something like this:

define(function (require) {

    "use strict";

    var $ = require('jquery');

    var hideAlert = function() {
        $('.alert').hide();
    };


    var loadURL = function (url){
            navigator.app.loadUrl(url, { openExternal:true });
            return false; 
    };


    var linkClicked = function (e) {    
        e.preventDefault();
        var url = $(e.currentTarget).attr("rel"); 
        loadURL(url);
    };


    return {
        hideAlert : hideAlert,
        loadURL : loadURL,
        linkClicked : linkClicked
    };

});

I would assume you set UsefulFuncs.linkClicked as a handler for an event.

If you were to use it like this:

UsefulFuncs.linkClicked()

, this inside the function would refer to UsefulFuncs , so this.loadURL() would be valid.

However, since you set it as a handler for an event, it can be called in other ways, and this is set to some other object (probably the element which triggered the event). To avoid the event handling mechanism changing your this , you can bind the function when you assign it:

element.onclick = UsefulFuncs.linkClicked.bind(UsefulFuncs);

Another way to go around it is to avoid using this in the handler, like so:

UsefulFuncs.linkClicked = function (e) {    
    e.preventDefault();
    var url = $(e.currentTarget).attr("rel"); 
    UsefulFuncs.loadURL(url);
};

This creates a closure over UsefulFuncs (the first method does as well, but it's more standardized).

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