简体   繁体   中英

Adding arbitrary functions to dom objects in javascript / jquery

I need to add some function that returns a value to a dom element. I tried to use jquery's bind method, but it seems that events always return a jquery collection.

My goal is creating a flashcard application. So I created flashcard objects that contain methods and variables including the dom element representing the flashcard on the page. As long as I only work on the dom element (moving around etc.) everything is fine but at some point I need to get a reference to the actual card object to access the additional functionality. Here is the constructor I came up with:

    function make_flashcard {  
        var dom_element;
        function some_function() {}
        /*...other variables and functions */

        var card = {
            dom_element: dom_element,
            some_function: some_function,
            /*...other variables and functions */
        };

        return card;
    }

later I'd like to be able to invoke some_function from outside, maybe like this:

    card = dom_element.get_card();
    card.some_function();

I tried the following three approaches of defining get_card inside make_flashcard, all of which failed:

    dom_element.get_card = function () {
        return card;
    };

    dom_element.prototype.get_card = function () {
        return card;
    };

or

    dom_element.bind("get_card", function () {
        return card;
    });

and then calling

    card = dom_element.trigger("get_card");

If you have any tips to get this running I'd be very happy. Or do you think the whole thing should be approached differently?

Thanks in advance, Dominik

`

What if you extended the jQuery collection prototype instead?

$.fn.flashcard = function () {
    var self = this;

    if (!this.data("flashcard")) {
        this.data("flashcard", {
           element: self,
           some_function: some_function,
           /*...other variables and functions */
        });
    }

    return this.data("flashcard");
};

Then you could use it like:

var card = $("div.myClass").flashcard();
card.some_function();

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