SitePoint Sponsor

User Tag List

Page 2 of 2 FirstFirst 12
Results 26 to 33 of 33
  1. #26
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,707
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    Tomorrow we should be able to use a similar selector for the container, and move the code below the roll function in to its own separate function for easy handling.
    That should help us to easily call the lotto function with our own custom selectors for the container and template, instead of needing to have them embedded within the lotto code.
    We can now fix up the container side of things, which currently starts out as:

    Code:
    container = document.getElementById('container'),
    templateSelector = '.lotto.template',
    playSelector = 'input',
    resultSelector = 'div';
    ...
    var content = document.querySelector(templateSelector).cloneNode(true),
    ...
    container.innerHTML = '';
    container.appendChild(content);
    We can use the same selector technique for the container. While we are here, I'll also make the play and result selectors a bit more specific too

    HTML Code:
    <input type="button" class="play">
    <div class="result"></div>
    Code javascript:
    containerSelector = '.lotto.container',
    templateSelector = '.lotto.template',
    playSelector = '.play',
    resultSelector = '.result';
    ...
    var container = document.querySelector(containerSelector),
        content = ...

    What we want to do is to move these selectors in to the opts object, but before we do that, we should first refactor the below code in to separate functions.

    Code:
    var container = document.querySelector(containerSelector),
        content = document.querySelector(templateSelector).cloneNode(true),
        playButton = content.querySelector(playSelector),
        resultDiv = content.querySelector(resultSelector);
    
    removeClass(content, 'template');
    
    playButton.id = "play" + idx;
    playButton.value = opts.buttonText;
    playButton.onclick = function justOnce() {
        this.blur();
        if (counter > 0) {
            return false;
        }
        roll();
    };
    
    resultDiv.id = "result" + idx;
    resultDiv.innerHTML = opts.initialText;
    
    container.innerHTML = '';
    container.appendChild(content);
    What do we have there, is code to setup the content from that template, and to update the container with that content.
    That's a lot of code for just one function, due to several responsibilities being involved, so what I want to do instead is to call an init function to get things going. That init function can then pass the opts info to where it's needed.

    Code javascript:
    init(opts) {
        var container = document.querySelector(opts.containerSelector),
            template = document.querySelector(opts.containerSelector),
            content = generateContentFromTemplate(template, opts);
     
        updateContainer(container, content);
    }

    That's how I want things to be structured.

    With the generateContentFromTemplate() function we can currently move the existing code in to that function.

    Code javascript:
    function generateContentFromTemplate(template, opts) {
        var content = document.querySelector(selector).cloneNode(true),
        playButton = content.querySelector(playSelector),
        resultDiv = content.querySelector(resultSelector);
     
        removeClass(content, 'template');
     
        playButton.id = "play" + idx;
        playButton.value = opts.buttonText;
        playButton.onclick = function justOnce() {
            this.blur();
            if (counter > 0) {
                return false;
            }
            roll();
        };
     
        resultDiv.id = "result" + idx;
        resultDiv.innerHTML = opts.initialText;
     
        return content;
    }
    ...
    content = generateContentFromTemplate(templateSelector, opts);

    We will come back to this later on, after the restructuring has occurred.

    After moving that code in to the function, the roll function can't find the resultDiv variable. Because two different places want to update the resultDiv, this is a good time to create a function called updateResult just for that purpose, where we can use the selector in opts.resultSelector to specify where the update occurs.

    Because the result that we want to update may be on the page, or it may be in the template content that we are working with, we will want to pass a context to the updateResult function too. We can also default that to the document object if none is provided.

    Code javascript:
    function updateResult(html, context) {
        context = context || document;
     
        var resultSelector = opts.resultSelector,
            result = context.querySelector(resultSelector);
     
        result.innerHTML = html;
    }
    ...
    var draw = ...,
        container = document.querySelector(containerSelector);
     
    ...
    updateResult(draw.join(' '), container);

    and the following line from generateContentFromTemplate() can be replaced too:

    Code:
    resultDiv = content.querySelector(opts.resultSelector);
    ...
    resultDiv.innerHTML = opts.initialText;
    updateResult(opts.initialText, content);
    Things are now ready for us to move the selectors in to the opts object.
    We can also get the selector first from the options passed to the lotto function, before defaulting to our default selectors. That way they can be overridden when calling the lotto function.
    We do though need to protect ourself from when lotto is called with no options.

    Code javascript:
    if (!options) {
        options = {};
    }
    var opts = {
        pick: options.pick || 6,
        from: options.from || 1,
        to: options.to || 49,
        containerSelector: options.containerSelector || '.lotto.container',
        templateSelector: options.templateSelector || '.lotto.template',
        playSelector: options.playSelector || '.play',
        resultSelector: options.resultSelector || '.result',
        totalRolls: options.totalRolls || 50,
        rollDelay: options.rollDelay || 50,
        buttonText: options.buttonText || "Lotto Lucky Dip",
        initialText: options.initialText || "Your Lucky Numbers"
    },

    They are listed in an approximate order of importance, but it's entirely up to you. You can list them, for example, in alphabetical order instead of yolu like.

    The move to the opts function means that some pieces of code now need to be updated, to retrieve the information from there.
    Thanks to the restructuring though, it's not many pieces at all though.

    Code javascript:
    var result = context.querySelector(opts.resultSelector);
    ...
    container = document.querySelector(opts.containerSelector);
    ...
    playButton = content.querySelector(opts.playSelector),
    resultDiv = content.querySelector(opts.resultSelector);
    ...
    var container = document.querySelector(opts.containerSelector),
    template = document.querySelector(opts.templateSelector);

    Another change that I'll want to make is to have the defaults specified separately, and to then loop through them adding them to any missing properties from the options, but that's for later on the todo list.

    Let us now get back to that generateContentFromTemplate function. Here's the current code that we'll be working on.

    Code:
    function generateContentFromTemplate(template, opts) {
        var content = template.cloneNode(true),
            playButton = content.querySelector(opts.playSelector),
            resultDiv = content.querySelector(opts.resultSelector);
    
        removeClass(content, 'template');
        
        playButton.id = "play" + idx;
        playButton.value = opts.buttonText;
        playButton.onclick = function justOnce() {
            this.blur();
            if (counter > 0) {
                return false;
            }
            roll();
        };
    
        resultDiv.id = "result" + idx;
        updateResult(opts.initialText, content);
    
        return content;
    }
    Here's what needs to be done with it:
    • the idx parts aren't needed at all
    • the play section could do with being extracted out to its own function
    • I'm not happy with that removeClass section


    Removing the idx parts is easy, and the variable declaration further up for is can be removed too.

    Code:
    idx = document.getElementsByTagName('div').length,
    ...
    playButton.id = "play" + idx;
    resultDiv.id = "result" + idx;
    The playButton code can be moved in to its own function, and called from within the generateContentFromTemplate one:

    Code javascript:
    function setupPlayButton(button, value) {
        button.value = value;
        button.onclick = function rollLottoNumbers() {
            this.blur();
            if (counter > 0) {
                return false;
            }
            roll();
        };
    }
    ...
    setupPlayButton(playButton, opts.buttonText);

    With the removeClass part, not only does it seem like a needless detail but it also results in the following nested div HTML structure for the container:

    HTML Code:
    <div class="lotto container">
        <div class="lotto">
            <!-- template content in here -->
        </div>
    </div>
    What would be good instead, is to remove that inner div - to unwrap it from the content.

    Let's move the problem out to a separate function, so that we can clean up the generateContentFromTemplate() function and focus on this last remaining problem.

    Code javascript:
    function generateContentFromTemplate(template, opts) {
        var content = getTemplateContent(template),
            playButton = content.querySelector(opts.playSelector),
            resultDiv = content.querySelector(opts.resultSelector);
     
        setupPlayButton(playButton, opts.buttonText);
        updateResult(opts.initialText, content);
     
        return content;
    }

    That function is now looking a lot better than it was.

    The getTemplateContent() function starts off like this:

    Code:
    function getTemplateContent(template) {
        var content = template.cloneNode(true);
        removeClass(content, 'template');
        return content;
    }
    What I want to do here is to create a document fragment, and copy the child nodes of the template over to there instead.

    Code javascript:
    function getTemplateContent(template) {
        var copyOfTemplate = template.cloneNode(true),
            content = document.createDocumentFragment();
     
        while (copyOfTemplate.hasChildNodes()) {
            content.appendChild(copyOfTemplate.firstChild);
        }
     
        return content;
    }

    And now the class-handling functions, such as removeClass that we had earlier, can now be removed.

    Lastly for now, the form-handling code should be moved out of the wrapper for the lotto code, and placed at the end below the wrapper. This allows the lotto code to be easily moved out to a separate javascript file.

    So now the lotto code can be started with just a call to lotto(), or other options can be given to it to change how it behaves.

    JSLint is still happy with all of the code, when we tell it to assume that we're using a browser, and there isn't much more with the refactoring left to be done.
    The code that we now have is found at http://jsfiddle.net/pmw57/8R42e/22/

    I hope you can agree that this refactoring has been worth it.

    Off Topic:

    Mad props to the SitePoint developers.

    I foolishly performed a web browser update while the preview for this post was left in an open tab, and I was able to retrieve ALL of this super-long post using the auto-restore content link.

    It seriously helps to alleviate a bad situation for me.
    Last edited by paul_wilkins; May 4, 2013 at 14:00. Reason: adjust a double "we can now" situation
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  2. #27
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,941
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    So, I just finished working through all of that (Phew!)
    This has really been a good learning experience in making code more readable and therefore by definition easier to maintain.
    I hadn't expected such an in-depth response when I posted my original question.
    Thank you!

    There was one last thing I wanted to ask: if we want multiple containers, how would we differentiate between them?

    Like this?

    HTML Code:
    <div class="lotto container"></div>
    <div class="lotto container2"></div>
    <div class="lotto container1"></div>
    
    etc...

  3. #28
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,707
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Pullo View Post
    So, I just finished working through all of that (Phew!)
    This has really been a good learning experience in making code more readable and therefore by definition easier to maintain.
    I hadn't expected such an in-depth response when I posted my original question.
    Thank you!

    There was one last thing I wanted to ask: if we want multiple containers, how would we differentiate between them?

    Like this?

    HTML Code:
    <div class="lotto container"></div>
    <div class="lotto container2"></div>
    <div class="lotto container1"></div>
    
    etc...
    No, adding numbers to the class name is a bad way to do that.

    The next stage of things that I'll take with the code, is how to make it work in multiple situations. Even if they seem to be identical.

    I'll get on to that tomorrow.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #29
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,941
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Sorry, I didn't want to cause you more work

    It was just that we discussed this briefly beforehand and this was the only way I could see to currently do it (or with an unique identifier).

    Also, what are your thoughts on making this code work with Handlebars (as Jeff Mott's suggestion in post#5)?

    I was just playing around with Handlebars and got it working ok, but couldn't see any added bonus it would bring in the light of how we currently have things set up.

  5. #30
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,707
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Pullo View Post
    Sorry, I didn't want to cause you more work

    It was just that we discussed this briefly beforehand and this was the only way I could see to currently do it (or with an unique identifier).
    What we has earlier wasn't as capable of being worked with what we now have, so it's a good opportunity to delve in to what needs to be done to allow such things to be worked on in a more flexible manner.

    Quote Originally Posted by Pullo View Post
    Also, what are your thoughts on making this code work with Handlebars (as Jeff Mott's suggestion in post#5)?

    I was just playing around with Handlebars and got it working ok, but couldn't see any added bonus it would bring in the light of how we currently have things set up.
    I agree. It's useful for larger projects, but overkill for what we're working with here.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #31
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,707
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    The next level of detail is to allow the code to run in multiple instances on the page. To achieve this, we cannot have the code always query the page for the section that it's working with. So we want the code to make only one query when it's being used, and to then refer to a stored reference of that query on future occasions.

    Currently there are 4 queries when the lucky dip starts. Two are for the container and the template, which are reasonable, and the other two are of the template for the play button and the result area, which are reasonable too.

    When the play button is pressed though, every single update of the numbers as they roll results in a search of the document for the container and for the result area, which is not reasonable. Those searches all need to be fixed so that rolling doesn't result in any searches at all.

    An effective way of doing that is to assign the container to the opts object, and retrieve that reference from the roll function.

    Code:
    var opts = {
        container: opts.container,
        ...
    };
    
    opts.container = opts.container || document.querySelector(opts.containerSelector);
    ...
    function roll() {
        ...
        container = opts.containerdocument.querySelector(opts.containerSelector);
        ...
    In fact, it could be useful to have all of the selectors resolved in the opts object, or to at least have a property there that is waiting for a reference to be assigned:

    Code javascript:
    var opts = {
        container: options.container,
        template: options.template,
        ...
    };
    opts.container = opts.container || document.querySelector(opts.containerSelector);
    opts.template = opts.template || document.querySelector(opts.templateSelector);
    opts.playButton = {};
    opts.resultArea = {};

    So a container or a template can be provided, and if they aren't then they will be assigned from the selector instead. For example:

    Code javascript:
    lotto({
        container: document.querySelector('#lotto1'),
        pick: 4,
        from: 1,
        to: 40
    });

    We can now make use of opts.container and opts.template in the init() function, where we can simplify the request for the container and template:

    Code:
    var container = opts.containerdocument.querySelector(opts.containerSelector),
        template = opts.templatedocument.querySelector(opts.templateSelector),
        content = generateContentFromTemplate(template, opts);
    and in the generateContentFromTemplate() function we can assign the play button and result area to the opts object, so that we may make good use of them later on:

    Code javascript:
    function generateContentFromTemplate(template, opts) {
        ...
        opts.playButton = content.querySelector(opts.playSelector);
        opts.resultArea = content.querySelector(opts.resultSelector);
     
        setupPlayButton(opts.playButton, opts.buttonText);
        updateResult(opts.initialText, template);
        ...

    So now that we have the result area defined, we don't need to pass a context to the updateResult() function anymore. We can instead make the resultArea() function a lot simpler now.

    Code javascript:
    function updateResult(html, resultArea) {
        resultArea.innerHTML = html;
    }
    ...
    //updateResult(draw.join(' '), [color="green"]container[/color][color="red"][s]opts.resultArea[/s][/color]);
    ...
    //updateResult(draw.join(' '), [color="green"]template[/color][color="red"][s]opts.resultArea[/s][/color]);

    And now the lucky dip can run in multiple different instances, without them interfering with each other.

    As a last bit for now, I want to just have the following HTML element that can then contain the lotto object:

    Code javascript:
    <div id="lotto2"></div>

    And to achieve that, I'll want to add the "lotto container" class names to the container. Previously I would have been tempted to do that manually, or use an addClass function, but there is now element.classList which we can use to get a list of classes on an object, and add/remove them too.

    So we can add the following to the init() function:

    Code javascript:
    container.classList.add('lotto');
    container.classList.add('container');

    and the following is all that's now needed to create a new lucky dip in a different location:

    Code javascript:
    lotto({
        container: document.querySelector('#lotto2')
    });

    Or even just:

    Code javascript:
    lotto({
        containerSelector: '#lotto2'
    });

    The test code with the above changes can be found at http://jsfiddle.net/pmw57/8R42e/23/

    The next thing on the TODO list is to rework the code in to a module pattern, which helps to give it a more well-known structure that can be easily maintained and extended.

    To do so using TDD to create unit tests, and perhaps intern might be an interesting way to explore such techniques.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #32
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,941
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Hi,

    It took a while to remember where we'd got to with this, but looking back through the old fiddles helped.
    I like the changes you made, preventing the roll() function from querying the DOM was an easy win.
    I do however have two questions:
    1. Why do you initialize these two properties as empty objects?

      Code JavaScript:
      opts.playButton = {};
      opts.resultArea = {};
      when later on you set them as:

      Code JavaScript:
      opts.playButton = content.querySelector(opts.playSelector);
      opts.resultArea = content.querySelector(opts.resultSelector);
      Isn't the first bit unnecessary?

    2. There is no button to update changes to the second (and subsequent) lotto instance(s).
      Shouldn't each lotto instance be associated with its own form controls?
      Or perhaps it would be nice to have one set of form controls and (for example) a select menu to choose which lotto instance to update.

      I just tried adding this functionality to what we have and one major problem that I ran into, is that we currently have no way of getting a reference to the current set of options for a particular lotto instance (that I could see).

      What do you think would be the best way to approach this problem?

    Quote Originally Posted by paul_wilkins View Post
    The next thing on the TODO list is to rework the code in to a module pattern, which helps to give it a more well-known structure that can be easily maintained and extended.
    That would be good.

    Quote Originally Posted by paul_wilkins View Post
    To do so using TDD to create unit tests, and perhaps intern might be an interesting way to explore such techniques.
    That would be even better and something I would like to learn more about.

  8. #33
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,707
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by Pullo View Post
    Why do you initialize these two properties as empty objects?
    Mostly it was to keep the variable assignments for all elements in just one place.
    It also helps though with allowing them to be accessed from other parts of the script too. It doesn't need to occur though, and if we later on have a user-supplied function to set up the template, they should be removed.

    Quote Originally Posted by Pullo View Post
    There is no button to update changes to the second (and subsequent) lotto instance(s).
    Sometimes you won't want to give the user the ability to change those settings. This lucky dip is capable of working in bot situations. A form to provide such controls is already here for one of them, so a demo of other uses without the form is also given too.

    Quote Originally Posted by Pullo View Post
    I just tried adding this functionality to what we have and one major problem that I ran into, is that we currently have no way of getting a reference to the current set of options for a particular lotto instance (that I could see).
    Yes, that can be easily dealt with by attaching the code and accessor functions on to the container itself. After getting some tests in place, we can make that sort of change and use the tests to ensure that things continue to work in a proper manner.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •