2

I'm building a custom widget system for an app I'm working on. What I want to have happen is the ability for one widget to update another widget by changing out the data attributes value. On page load, the initial data is loaded into this data-attr via PHP and using jQuery to switch out the data after the fact.

For instance, one widget would work as follows:

  • PHP loads json data into DOM element
  • jQuery function is passed the elements ID and retrieves data from data-attr and uses it to produce a graph for example
  • Based on user interaction, another widget sends data to element's data-attr while also firing a custom jQuery event
  • Initial function gets the new data and updates it's graph

I've started a demo:

// Ranomize Number & Replace Variable
$(function() {
  $('#random').click(function(e) {
    e.preventDefault();
    num = Math.random() + 100;
    $('#data').attr('data-receiver', num);
  });
});

// Receive Data & Output
$(function() {
  var output = $('#output');
  var received = $('#data').attr('data-receiver');
  output.html(received);

  // Not sure what to do next
});
#content {
  background: #efefef;
  margin: 40px auto;
  display: block;
  padding: 50px;
  width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
  <div id="data" data-receiver="10"></div>
  <strong>Output:</strong>
  <span id="output"></span>
  <br/>
  <br/>
  <a href="#" id="random">Randomize</a>
</div>

But to be honest I'm not sure how to start. I have some code putting a random value into the receiving DOM element, but not sure how to setup the event or write another function to receive and update the #output div.

I'm happy to answer questions or write more code to help better explain my goal. Thanks in advance.

8
  • If you want to do a custom event you can do $(selector).on('whatever', callbackFunction); Then it can be executed with $(selector).trigger('whatever'); Commented May 11, 2015 at 23:28
  • So if hypothetically I have two functions: sender() and receiver() to send and receive data from the DOM element, which one do I place as the callbackFunction? Commented May 11, 2015 at 23:30
  • Do you want both of these elements to talk together with sender() and receiver()? Commented May 11, 2015 at 23:33
  • Sorry both elements? The idea is that data flows like this sender_func( trigger event ) -> DOM element data-attr -> receiver_func( gets data when trigger occurs ). So there is one element in the middle. The idea is that I will build a view, the function on the receiver side will get data on load, IF it's data ever gets updated, it then gets the new data and does what it needs. If it doesn't ever get data, then it never changes. Commented May 11, 2015 at 23:37
  • Something like this maybe? jsfiddle.net/6s65myhr Commented May 11, 2015 at 23:49

2 Answers 2

2

Try utilizing .queue() , .promise() to create a "subscriber" , "publisher" pattern

var output = $("#output");

var process = function process(next) {
    // `this`:`#data`
    var num = Math.random() * 100;
    $(this).data("receiver", num);
    return next()
};

var update = function update() {
  // `this`:`#data`
  $(this).promise("process").then(function(received) {
    // `received`:`#data`,
    // do stuff with `received`
    console.log(received.data("receiver"));
    output.html(received.data("receiver"));
    received.queue("process", process);
    // add `process` to `received` `"process"` queue
    console.log(received, received.queue("process"));
  });
};

// queue first call to `process`
$("#data").queue("process", process);

$("#random").click(function (e) {
    e.preventDefault();        
    update.call($("#data").dequeue("process"));       
});

jsfiddle http://jsfiddle.net/jev4wuej/2/

Sign up to request clarification or add additional context in comments.

2 Comments

What's the benefit of the subscriber / publisher pattern versus the method I was outlining (for my growth of knowledge).
@dvoutt Not certain about exact meaning of "benefit" ? Depends on how "benefit" defined ? Separating portions , "layers" , or "steps" into distinct blocks performing distinct parts of a "process" ? Ability to add catch error , add error callbacks; other processes to each "part" block ? "What I want to have happen is the ability for one widget to update another widget by changing out the data attributes value." See api.jquery.com/jQuery.Callbacks/#pubsub
1

I prefer to use custom events which allows for the code to be more decoupe and independent of each other.

jsfiddle

JS

var toolbar = {
    init: function() {
        $('.data-randomizer').click(this.handleRandomizer);
    },
    handleRandomizer: function() {
        var number = Math.random() + 100;
        $.event.trigger('update-request.storage-widget', [number]);
    }
};
var output = {
    init: function() {
        $(document).on('updated.storage-widget', this.handleDisplay);
        $.event.trigger('data-request.storage-widget', this.handleDisplay);
    },
    handleDisplay: function(event, number) {
        $('.data-output-widget #output').text(number);
    },
    requestOut: function() {

    }
};
var storage = {
    init: function() {
        $(document).on('update-request.storage-widget', this.handleUpdateRequest);
        $(document).on('data-request.storage-widget', this.handleDataRequest);
    },
    handleUpdateRequest: function(event, number) {
        $('.data-storage-widget').attr('data-receiver', number);
        $.event.trigger('updated.storage-widget', [number]);
    },
    handleDataRequest: function(event, callback) {
        var number = $('.data-storage-widget').data('receiver');
        callback(event, number);
    }
};

toolbar.init();
storage.init();
output.init();

HTML

<div id="content">
    <div class="data-storage-widget" data-receiver="10"></div>
    <div class="data-output-widget">
        <strong>Output:</strong>
        <span id="output"></span>
    </div>
    <div class="tool-bar-widget">
         <a href="javascript:void(0)" class="data-randomizer">Randomize</a>
    </div>

</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.