开发者

Functional object basics. How to go beyond simple containers?

On the upside I'm kinda bright, on the downside I'm wracked with ADD. If I have a simple example, that fits with what I already understand, I get it. I hope someone here can help me get it.

I've got a page that, on an interval, polls a server, processes the data, stores it in an object, and displays it in a div. It is using global variables, and outputing to a div defined in my html. I have to get it into an object so I can create multiple instances, pointed at different servers, and managing their data seperately.

My code is basically structured like this...

HTML...

<div开发者_开发问答 id="server_output" class="data_div"></div>

JavaScript...

// globals
var server_url = "http://some.net/address?client=Some+Client";
var data = new Object();
var since_record_id;
var interval_id;

// window onload
window.onload(){

  getRecent();

  interval_id = setInterval(function(){
    pollForNew();
  }, 300000);
}

function getRecent(){
  var url = server_url + '&recent=20';
  // do stuff that relies on globals
  // and literal reference to "server_output" div.
}

function pollForNew(){
  var url = server_url + '&since_record_id=' + since_record_id;
  // again dealing with globals and "server_output".
}

How would I go about formatting that into an object with the globals defined as attributes, and member functions(?) Preferably one that builds its own output div on creation, and returns a reference to it. So I could do something like...

dataOne = new MyDataDiv('http://address/?client');
dataOne.style.left = "30px";

dataTwo = new MyDataDiv('http://different/?client');
dataTwo.style.left = "500px";

My code is actually much more convoluted than this, but I think if I could understand this, I could apply it to what I've already got. If there is anything I've asked for that just isn't possible please tell me. I intend to figure this out, and will. Just typing out the question has helped my ADD addled mind get a better handle on what I'm actually trying to do.

As always... Any help is help.

Thanks

Skip

UPDATE: I've already got this...

$("body").prepend("<div>text</div>");
this.test = document.body.firstChild;
this.test.style.backgroundColor = "blue";

That's a div created in code, and a reference that can be returned. Stick it in a function, it works.

UPDATE AGAIN: I've got draggable popups created and manipulated as objects with one prototype function. Here's the fiddle. That's my first fiddle! The popups are key to my project, and from what I've learned the data functionality will come easy.


This is pretty close:

// globals
var pairs = {
    { div : 'div1', url : 'http://some.net/address?client=Some+Client' } ,
    { div : 'div2', url : 'http://some.net/otheraddress?client=Some+Client' } ,
};

var since_record_id; //?? not sure what this is
var intervals = [];

// window onload
window.onload(){  // I don't think this is gonna work

    for(var i; i<pairs.length; i++) {
        getRecent(pairs[i]);
        intervals.push(setInterval(function(){
            pollForNew(map[i]);
        }, 300000));
    }
}

function getRecent(map){
    var url = map.url + '&recent=20';
    // do stuff here to retrieve the resource
    var content = loadResoucrce(url);  // must define this
    var elt = document.getElementById(map.div);
    elt.innerHTML = content;
}

function pollForNew(map){
    var url = map.url + '&since_record_id=' + since_record_id;
    var content = loadResoucrce(url); // returns an html fragment
    var elt = document.getElementById(map.div);
    elt.innerHTML = content;
}

and the html obviously needs two divs:

<div id='div1' class='data_div'></div>
<div id='div2' class='data_div'></div>

Your 'window.onload` - I don't think that's gonna work, but maybe you have it set up correctly and didn't want to bother putting in all the code.

About my suggested code - it defines an array in the global scope, an array of objects. Each object is a map, a dictionary if you like. These are the params for each div. It supplies the div id, and the url stub. If you have other params that vary according to div, put them in the map.

Then, call getRecent() once for each map object. Inside the function you can unwrap the map object and get at its parameters.

You also want to set up that interval within the loop, using the same parameterization. I myself would prefer to use setTimeout(), but that's just me.

You need to supply the loadResource() function that accepts a URL (string) and returns the HTML available at that URL.


This solves the problem of modularity, but it is not "an object" or class-based approach to the problem. I'm not sure why you'd want one with such a simple task. Here's a crack an an object that does what you want:

(function() {

    var getRecent = function(url, div){
        url = url + '&recent=20';
        // do stuff here to retrieve the resource
        var content = loadResoucrce(url);  // must define this
        var elt = document.getElementById(div);
        elt.innerHTML = content;
    }

    var pollForNew =  function(url, div){
        url = url + '&since_record_id=' + since_record_id;
        var content = loadResoucrce(url); // returns an html fragment
        var elt = document.getElementById(div);
        elt.innerHTML = content;
    }

    UpdatingDataDiv = function(map) {
        if (! (this instanceof arguments.callee) ) {
            var error = new Error("you must use new to instantiate this class");
            error.source = "UpdatingDataDiv";
            throw error;
        }

        this.url = map.url;
        this.div = map.div;
        this.interval = map.interval || 30000; // default 30s
        var self = this;

        getRecent(this.url, this.div);

        this.intervalId = setInterval(function(){
            pollForNew(self.url, self.div);
        }, this.interval);
    };

    UpdatingDataDiv.prototype.cancel = function() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
    }

})();

var d1= new UpdatingDataDiv('div1','http://some.net/address?client=Some+Client');
var d2= new UpdatingDataDiv('div2','http://some.net/otheraddress?client=Some+Client');
   ...
 d1.cancel();

But there's not a lot you can do with d1 and d2. You can invoke cancel() to stop the updating. I guess you could add more functions to extend its capability.


OK, figured out what I needed. It's pretty straight forward.

First off disregard window.onload, the object is defined as a function and when you instantiate a new object it runs the function. Do your setup in the function.

Second, for global variables that you wish to make local to your object, simply define them as this.variable_name; within the object. Those variables are visible throughout the object, and its member functions.

Third, define your member functions as object.prototype.function = function(){};

Fourth, for my case, the object function should return this; This allows regular program flow to examine the variables of the object using dot notation.

This is the answer I was looking for. It takes my non-functional example code, and repackages it as an object...

function ServerObject(url){
  // global to the object
  this.server_url = url;
  this.data = new Object();
  this.since_record_id;
  this.interval_id;

  // do the onload functions
  this.getRecent();

  this.interval_id = setInterval(function(){
    this.pollForNew();
  }, 300000);

  // do other stuff to setup the object

  return this;
}

// define the getRecent function
ServerObject.prototype.getRecent = function(){
  // do getRecent(); stuff
  // reference object variables as this.variable;
}

// same for pollForNew();
ServerObject.prototype.pollForNew = function(){  
  // do pollForNew(); stuff here.
  // reference object variables as this.variable;
}

Then in your program flow you do something like...

var server = new ServerObject("http://some.net/address");
server.variable = newValue; // access object variables

I mentioned the ADD in the first post. I'm smart enough to know how complex objects can be, and when I look for examples and explanations they expose certain layers of those complexities that cause my mind to just swim. It is difficult to drill down to the simple rules that get you started on the ground floor. What's the scope of 'this'? Sure I'll figure that out someday, but the simple truth is, you gotta reference 'this'.

Thanks

I wish I had more to offer.

Skip

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜