开发者

calling and dynamically updating jquery functions

I am trying to implement jquery replacement开发者_运维知识库 for the old periodically_call_remote. I got the following code from another stackoverflow thread here:

$(document).ready(
  function(){
    setInterval(function(){
      $('#mydiv').load('/controller/action');
    }, 3000);
  });

But I am struggling to make it work. If I understand UJS correctly, if I do the following things:

  • Place the script in application.js
  • include application.js in my layout (which javascript_include_tag :defaults does)
  • have a DOM element in my view template with id='mydiv'

Then the function should automatically bind to 'mydiv' and execute after the page is loaded, right? Is there a step I am missing? I should not have to name the function or call it directly in the view, correct?

Second, how can I dynamically update the load URL. For instance, I have a nested resource with the path '/controller/:id/action' ... how do I dynamically insert the :id value into the load path at render time?


The way to do this unobtrusively is to set an attribute in the div tag that you want to load and then grab it from within the application.js file.

some.html

<div data-delay-load="<%= url_for() %>"></div>

application.js

$(function() {

    $('div[data-delay-load]').each( function() {
        var url = $(this).attr('data-delay-load'),
            $element = $(this);

        var _func = function() {
           $element.load(url);
        }

        setTimeout(_func, 3000);
    });
});

What is nice is that you can have a delay load on any page or multiple elements on the same page just by including the data-delay-load attribute.


Add the following inside you functions.

$('#mydiv').css("background", "red");

Did the color of the div change? If it did, debug your server side code.

If you know how to open a JavaScript console in your browser, open it and see if there are any errors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜