Listening to multiple events in a row from various objects

I am currently in the process of developing an iOS app using Titanium. Within my app, I have a tableview that consists of two images and various labels on each row. My goal is to allow users to click on either of the images to swap them with other images, as well as click on a label (such as a phone number) to prompt the dialer. At the moment, clicking anywhere within the row triggers the image swap functionality. Below is a snippet of the code I am working with:

//First, I set up my table and make a call to a PHP file to retrieve JSON data. I then proceed to create rows and define an image element

row = Ti.UI.createTableViewRow({
    backgroundImage: 'images/openmatchesrowbackground.png',
    selectionStyle: Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
    width: '100%',
    height: '180pt',
    rowId: i
});

var acceptmatchView = Ti.UI.createView({
    left: '0pt',
    top: '0pt',
    width: '60pt',
    height: '60pt'
});

var acceptmatch = Ti.UI.createImageView({
    image: 'images/nomatch.png',
    left: '0pt',
    top: '0pt',
    width: '60pt',
    action: 'swapImages',
    height: '60pt'
});

//Following this, I add some labels and append everything to the row - Next, I establish an event listener

tableview.addEventListener('click', function(e) {
    var imageView = e.row.children[0].children[0];

    if (imageView.image == 'images/nomatch.png') {
        imageView.image = 'images/match.png';

        var matchSelected = json.openmatches[e.rowData.rowId];

        var alertWindow = Titanium.UI.createAlertDialog({
            title: 'Accept This Match?',
            message: 'Are you sure you want to accept this match?' + '\n' + matchSelected.matchtype + '\n' + 'Time: ' + matchSelected.datetime + '\n' + 'At: ' + matchSelected.courtname,
            cancel: 1,
            buttonNames: ['Yes', 'Cancel']
        });

        alertWindow.addEventListener('click', function(ev) {
            Titanium.API.info("cancel " + ev.cancel);
            Titanium.API.info("index " + ev.index);

            switch(e.source.action){
                case 'swapImages':
                    break;
                case 'swapImages':
                    imageView.image = 'images/nomatch.png';
                    break;

            }
        });
        alertWindow.show();

    } else {
        //Logic for cancelling a match here
        //Similar structure as above

    }
});

tableview.setData(tableData);

My question is regarding how to structure my code so that it can efficiently handle interactions with each object within the row.

Answer №1

Aside from Dawson Toth's response, consider changing the bubbleParent property to false. This way, events may not propagate to the parent element in your specific scenario. By attaching an event listener to the tableViewRow, any interaction with the child will typically trigger an action on the parent as well. The default value for bubbleParent is set to true, but by setting it to false, you can prevent this cascading effect.

    var acceptmatchView = Ti.UI.createView({
        left : '0pt',
        top : '0pt',
        width : '60pt',
        height : '60pt',
        bubbleParent: false
        });

    var acceptmatch = Ti.UI.createImageView({
        image : 'images/nomatch.png',
        left : '0pt',
        top : '0pt',
        width : '60pt',
        action: 'swapImages',
        height : '60pt',
        bubbleParent: false
        });

Answer №2

To enhance functionality, consider including a property like action: 'swapImages' in the elements that trigger image swapping when clicked. You can also incorporate additional actions such as action: 'dial'. Within your click event listener, utilize a switch statement based on the action property to handle different functionalities. This method has proven effective for me across various applications.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to eliminate a JSON header?

Here is the JSON data I have: { "folder": [ { "$": { "id": "471841542", "name": "Manajemen Pemasaran", "description": "", "user_id": "186868958", "shared": "1", "shared_l ...

Vue.js - Exploring methods to append an array to the existing data

I am looking to structure my data in the following way: Category 1 Company 1 Company 2 Company 3 Category 2 Company 1 Company 2 Company 3 Below is my code snippet: getlist() { var list = this.lists; var category this.$htt ...

Display a custom dropdown menu depending on the value chosen from a separate dropdown menu

There are three dropdown lists, each enclosed in its own DIV container. The DIV containers are named fromCity, WithinStateLimits, and OutOfState. The goal is to use the jQuery script below to hide the other two DIVs when a user selects an option from the ...

VueJS error: Trying to access properties of undefined object ('$refs') is unsuccessful

Parent Component: ... <v-stepper-step :rules="[()=>isValid(1)]" > MyStep </v-stepper-step> <v-stepper-content> <Mytag ref="MyReference" /> </v-stepper-content> ... methods: { isValid(number){ ...

Utilizing JavaScript to control the visibility of a div based on radio button selection without the need

I am facing an issue with my HTML code that is only partially working. I am attempting to display text inputs based on a radio button selection. At the moment, the code successfully hides the other options when a radio button is clicked, but upon the ini ...

Dealing with 404 Errors in AngularJS using ui-router's resolve feature

As a newcomer to AngularJS and ui-router, I am currently facing the challenge of handling 404 errors for resources not found. My goal is to display an error message without changing the URL in the address bar. Here is how I have configured my states: app ...

Updating the default color of selected text within a webpage's content

Is there a way to modify the default blue color that appears when content is selected on a webpage? I am wondering how to change this selection color to a custom color of choice. ...

Tips for retrieving data from Angular dropdown menus

How to Retrieve Selected Value in AngularJS HTML <select data-ng-model='datasource.value' ng-options='sourcetype.dataSourceType as sourcetype.dataSourceDesc for sourcetype in sourcetypes' data-ng-change="getAccountCredentials(sourc ...

Having trouble with my React Next app, it's giving me an error stating "window is not defined

Currently, I am developing in Next.js using React components and encountering an issue. I keep receiving a ReferenceError: window is not defined error in react-location-picker. If you need to check out the package, here is the link: react-location-picker ...

Converting JSON to NSDictionary. Why does it have to be so difficult?

I encountered an issue when attempting to populate an NSDictionary with JSON data. The error I'm facing is due to the fact that the key is not being recognized. The specific error message reads: *The error[__NSCFArray objectForKey:]: unrecognized se ...

Change to JSONArray using angularjs

Here is a json object: "values": [ {"name": "name1"}, {"name": "name2"}, {"name": "name3"} ] I want to convert it into this format: values: ["name1", "name2", "name3"]; Can this conversion be done in AngularJS or any other JavaScript functi ...

How can one efficiently process a JSON array in Swift?

I am new to coding with Swift and I am attempting to send an HTTP request in Swift. Although I have managed to send the request, I am encountering difficulties parsing the response. Despite extensive research, I have not been successful in finding a solut ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...

What is the process for changing the state of an array in graphql?

Currently, I am facing a challenge with adding an array to a GraphQl schema. Here is what it looks like: type Play { winRatio: [Float] } The intention behind the winRatio attribute is to store the history of all win ratios. For instance, after playing 3 ...

Is there a way to retrieve values from two input fields using the onclick function?

In a div, I have added two input fields and an update button. Here's the code structure: <button type = "button" id = "add-botton" >Add Element </button> <div id = "trace-div1" class = "trace"> <h4><span>Trace 1& ...

Angular HTTP requests are failing to function properly, although they are successful when made through Postman

I am attempting to send an HTTP GET request using the specified URL: private materialsAPI='https://localhost:5001/api/material'; setPrice(id: any, price: any): Observable<any> { const url = `${this.materialsURL}/${id}/price/${price}`; ...

What is the best way to determine if a JSON response value contains a hyphen '-' in Java Script?

When I receive a JSON response, I sometimes encounter values with hyphens. In JavaScript, the hyphen '-' is treated as a subtraction operator. JSON books": { "red": "2008-17801", "blue": "TERTERIAN-HAYK" } After obtaining these values, I store ...

List Elements Not Displaying Correctly due to CSS Styling Issues

After spending several hours trying to solve this problem, I've hit a roadblock. The challenge lies in dynamically adding items to a list using JavaScript and the Dojo library. I've experimented with both vanilla JS and Dojo code, ruling that pa ...

Developing a timeline using a JSON file and dynamically altering the page based on the specified datetime within the JSON data

I am currently working on a project that involves a JSON file containing information about missions. This JSON file is subject to continuous updates and has a specific structure as shown below: [ { "module_id": 5, "title": "TITLE 1", "media ...

Troubles encountered when creating select/drop-down optgroup using jquery

Looking to incorporate the <optgroup> tag into a dropdown with JQuery. The option works as expected, but struggling with getting the option group to function correctly. Here's the HTML setup: <select name="DropDownID" id="DropDownID"> ...